package com.cxb.manager;

import java.lang.reflect.Method;
import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.net.Uri;
import android.os.SystemClock;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;

import com.cxb.R;
import com.cxb.entity.ApnNode;
import com.cxb.entity.Gps;
import com.cxb.entity.GpsDestinationInfo;
import com.cxb.utils.Config;
import com.cxb.utils.DBHelp;
import com.cxb.utils.Debug;
import com.cxb.utils.HttpEngineUtils;
import com.cxb.utils.SharedPreferencesUtils;
import com.cxb.view.TTSToast;

public class PhoneManager {
	private Context mContext = null;
	private static long startActiveTime = 0;
	private static String conectingPhoneNumber = null;
	private static AudioManager am = null;

	private static int alarmVolume = -1;
	private static int musicVolume = -1;
	public static GpsDestinationInfo gpsDestination = null;
	private SharedPreferencesUtils spUtils;
	private HttpEngineUtils httpEngineUtils;
	private AudioManager audioManager;

	public static final int SIM_CAR_TYPE_NORMAL = 0x01;// SIM类型普通，根据手机号码充值
	public static final int SIM_CAR_TYPE_IOT = 0X02;// 物联网卡，根据 iccid进行充值
	public static final int SIM_CAR_TYPE_UNKNOWN = 0X03;// 未知

	/**
	 * 电话状态，设置为静态全局
	 */
	public enum PhoneState {
		IDLE, RING, ACTIVE, DIALING;
	}

	public static PhoneState callState = PhoneState.IDLE;

	public PhoneManager(Context context) {
		mContext = context;
		am = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
		spUtils = new SharedPreferencesUtils(context);
		httpEngineUtils = new HttpEngineUtils(context);
		audioManager = (AudioManager) context
				.getSystemService(Context.AUDIO_SERVICE);
	}

	public static PhoneState getCallState() {
		return callState;
	}

	public void setCallState(PhoneState nState) {
		if (callState != nState) {
			Debug.printf("oldState=" + callState.toString() + " newState="
					+ nState.toString(), null);
			callState = nState;
			if (callState == PhoneState.ACTIVE) {
				startActiveTime = SystemClock.elapsedRealtime();

			} else
				startActiveTime = 0;

			if (callState == PhoneState.IDLE) {
				audioManager.setSpeakerphoneOn(false);
				if (alarmVolume != -1) {
					am.setStreamVolume(AudioManager.STREAM_ALARM, alarmVolume,
							0);
					alarmVolume = -1;
				}

				if (musicVolume != -1) {
					am.setStreamVolume(AudioManager.STREAM_MUSIC, musicVolume,
							0);
					musicVolume = -1;
				}
			} else {
				am.setSpeakerphoneOn(true);
				if (alarmVolume == -1) {
					alarmVolume = am.getStreamVolume(AudioManager.STREAM_ALARM);
					am.setStreamVolume(AudioManager.STREAM_ALARM, 0, 0);
				}

				if (musicVolume == -1) {
					musicVolume = am.getStreamVolume(AudioManager.STREAM_MUSIC);
					am.setStreamVolume(AudioManager.STREAM_MUSIC, 0, 0);
				}
			}
		}
	}

	public static long getActiveTime() {
		if (startActiveTime == 0)
			return 0;
		return (SystemClock.elapsedRealtime() - startActiveTime) / 1000;
	}

	public static String getConectingPhoneNumber() {
		return conectingPhoneNumber;
	}

	public static void setConectingPhoneNumber(String number) {
		conectingPhoneNumber = number;
	}

	public String getContactName(String phone) {
		if (phone == null || "".equals(phone)) {
			return "未知";
		} else if (phone.equals(spUtils.getCallNumber())) {

			return mContext.getString(R.string.phone_one_stone);
		} else if (phone.equals(spUtils.getSOSNumber())) {
			return mContext.getString(R.string.phone_rescue);
		}
		return phone;
	}

	public void endCall() {
		PhoneManager.setConectingPhoneNumber(null);
		Class<TelephonyManager> c = TelephonyManager.class;
		Method getITelephonyMethod = null;
		try {
			getITelephonyMethod = c.getDeclaredMethod("getITelephony",
					(Class[]) null);
			getITelephonyMethod.setAccessible(true);

			TelephonyManager tManager = (TelephonyManager) mContext
					.getSystemService(Context.TELEPHONY_SERVICE);
			Object iTelephony = getITelephonyMethod.invoke(tManager,
					(Object[]) null);
			Method endCall = iTelephony.getClass().getDeclaredMethod("endCall");
			endCall.invoke(iTelephony);
		} catch (Exception e) {
			e.printStackTrace();
		}
		setCallState(PhoneState.IDLE);
	}

	/**
	 * 直接去电
	 */
	public void call(String number) {
		if (!isSimCardAccess()) {
			TTSToast.show(mContext, mContext.getString(R.string.sim_error), 0);
			return;
		}
		/**
		 * add by eric 正在呼叫呼叫中心号码
		 */
		if (spUtils.getCallNumber() != null
				&& spUtils.getCallNumber().equals(number)) {
			CxbEventBus.getCxbBus(CxbEventBus.EVENT_REQUEST_NAVATION).post(
					new Object());
		}
		PhoneManager.setConectingPhoneNumber(number);
		// setCallState(PhoneState.DIALING);//未装卡或其它原因导致拨号失败时不会接收到状态消息,会导致媒体音量静音
		Intent iCall = new Intent(Intent.ACTION_CALL,
				Uri.parse("tel:" + number));
		// 通知activtity处理传入的call服务
		iCall.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		mContext.startActivity(iCall);
	}

	public boolean isSimCardAccess() {
		TelephonyManager telManager = (TelephonyManager) mContext
				.getSystemService(Context.TELEPHONY_SERVICE);
		boolean flag = false;
		switch (telManager.getSimState()) {
		case TelephonyManager.SIM_STATE_READY:
			flag = true;
			break;
		case TelephonyManager.SIM_STATE_ABSENT:// 无SIM卡
			flag = false;
			break;
		default:// SIM卡被锁定或未知状态
			flag = false;
			break;
		}
		return flag;
	}

	public synchronized void answerRingingCall() {
		Class<TelephonyManager> c = TelephonyManager.class;
		Method getITelephonyMethod = null;
		try {
			getITelephonyMethod = c.getDeclaredMethod("getITelephony",
					(Class[]) null);
			getITelephonyMethod.setAccessible(true);
			TelephonyManager tManager = (TelephonyManager) mContext
					.getSystemService(Context.TELEPHONY_SERVICE);
			Object iTelephony = (Object) getITelephonyMethod.invoke(tManager,
					(Object[]) null);
			Method answerRingingCall = iTelephony.getClass().getDeclaredMethod(
					"answerRingingCall");
			answerRingingCall.invoke(iTelephony);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public String getDeviceId() {
		try {

			TelephonyManager telephonyManager = (TelephonyManager) mContext
					.getSystemService(Context.TELEPHONY_SERVICE);
			String imei = telephonyManager.getDeviceId();
			if ("".equals(imei) || imei == null) {
				Log.i("test", "getDeviceId is null ,to get from root imei="
						+ imei);
				String phoneInfo = RootContext
						.runCommandForResult("dumpsys iphonesubinfo");
				if (TextUtils.isEmpty(phoneInfo)) {
					return null;
				}
				String[] strArrays = phoneInfo.split(" ");
				imei = strArrays[strArrays.length - 1];
				Log.i("test", "imei=" + imei);
				return imei;
			}
			return imei;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public String getSimIccid() {
		try {

			TelephonyManager telephonyManager = (TelephonyManager) mContext
					.getSystemService(Context.TELEPHONY_SERVICE);
			String iccid = telephonyManager.getSimSerialNumber();
			return iccid;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public String getSimImsi() {
		try {

			TelephonyManager telephonyManager = (TelephonyManager) mContext
					.getSystemService(Context.TELEPHONY_SERVICE);
			String iccid = telephonyManager.getSubscriberId();
			return iccid;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public String getPhoneNumber() {
		try {

			TelephonyManager telephonyManager = (TelephonyManager) mContext
					.getSystemService(Context.TELEPHONY_SERVICE);

			return telephonyManager.getLine1Number();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public int getSIMType() {

		TelephonyManager telManager = (TelephonyManager) mContext
				.getSystemService(Context.TELEPHONY_SERVICE);

		String imsi = telManager.getSubscriberId();
		if (imsi == null) {
			return SIM_CAR_TYPE_UNKNOWN;
		} else if (imsi.startsWith("46001")) {
			return SIM_CAR_TYPE_NORMAL;
		} else if (imsi.startsWith("46006")) {
			return SIM_CAR_TYPE_IOT;
		}

		return SIM_CAR_TYPE_UNKNOWN;

	}

	public ApnNode getSuitableAPN() {
		TelephonyManager mTelephonyManager = (TelephonyManager) mContext
				.getSystemService(Context.TELEPHONY_SERVICE);
		String imsi = mTelephonyManager.getSubscriberId();//460062051021462
		String iccid = mTelephonyManager.getSimSerialNumber();//89860616010021088469
		ApnNode apnNode = new ApnNode();
		if (imsi == null) {
			return null;
		} else if (imsi.startsWith("46001")) {
			return null;
		} else if (imsi.startsWith("46006")) {
			if (Config.isEcardSupport(mContext)) {
				apnNode.setApn("UNIM2M.GZM2MAPN");
				apnNode.setMcc("460");
				apnNode.setMnc("06");
				apnNode.setName("eCard");

			} else if (iccid.startsWith("8986061")) {//89860615090010642972
				apnNode.setApn("UNIM2M.NJM2MAPN");
				apnNode.setMcc("460");
				apnNode.setMnc("06");
				apnNode.setName("NJM2M");
			}
			return apnNode;
		}
		return null;
	} 
}
